import { HttpCacheService } from '@core/net/http-cache.service';
/* API服务示例 */
import { Injectable } from '@angular/core';
import { ApiService } from '@core/net/api.service';
import { IHttpRes } from '@core/net/HttpResponse';
import { TOKEN, USER_AUTH, USER_INFO, USER_MENU } from '@app/store/dict';



@Injectable({
	providedIn: "root"
})
export class LoginService {

	constructor(
		private apiService: ApiService,
		private httpCacheService: HttpCacheService
	) {
	}
	login(body): Promise<IHttpRes<string>> {
		return this.apiService.post('/sys/login', null, { params: body }).toPromise();
	}

	logout(): Promise<IHttpRes<any>> {
		return this.apiService.post('/sys/logout').toPromise();
	}
	/**
	 * 获取当前用户信息
	 * @returns
	 */
	getUserInfoData() {
		return this.apiService.post('/sys/user/getUserInfo').toPromise();
	}

	/**
	 * 修改登录用户密码
	 * @param body 
	 * @returns 
	 */
	modifyPassword(body): Promise<IHttpRes<any>> {
		return this.apiService.post('/sys/user/password', body).toPromise();
	}
	resetPassword(id): Promise<IHttpRes<any>> {
		return this.apiService.post('/sys/user/resetPassword?id=' + id).toPromise();
	}
	saveUserInfo(userInfo) {
		this.httpCacheService.saveSessionCache(USER_INFO, JSON.stringify(userInfo));
	}

	getUserInfo() {
		const userInfo = this.httpCacheService.getSessionCache(USER_INFO);
		if (userInfo) {
			return JSON.parse(userInfo);
		}
	}

	clearUserInfo() {
		this.httpCacheService.removeSessionCache(USER_INFO);
		this.httpCacheService.removeSessionCache(TOKEN);
		this.httpCacheService.removeSessionCache(USER_MENU);
		this.httpCacheService.removeSessionCache(USER_AUTH);

	}
	getToken() {
		return this.httpCacheService.getSessionCache(TOKEN) || '';
	}

	saveMenu(menu) {
		const cache = [];
		this.httpCacheService.saveSessionCache(USER_MENU, JSON.stringify(menu, function (key, value) {
			if (typeof value === 'object' && value !== null) {
				if (cache.indexOf(value) !== -1) {
					return;
				}
				cache.push(value);
			}
			return value;
		}));

	}
	getMenu() {
		const menu = this.httpCacheService.getSessionCache(USER_MENU);
		if (menu) {
			return JSON.parse(menu);
		}
	}
	/**
	 * 登陆人菜单显示
	 * @returns 
	 */
	getShowMenu() {
		return this.apiService.get('/sysResource/show').toPromise();
	}


	/**
	 * 登陆人权限显示
	 * @returns 
	 */
	getPermissions() {
		return this.apiService.post('/sysResource/permissions').toPromise();
	}

	
}
